const mongoose = require('mongoose')
const Schema = mongoose.Schema
const ObjectId = Schema.Types.ObjectId
const bcrypt = require('bcryptjs')
const SALT_WORK_FACTOR = 8  //8位盐权重

const UserSchema = new Schema({
    userName: {
        type: String,
        required: true
    },
    userPass: {
        unique: true,
        type: String
    },
    userPhone: {
        type: String,
        required: true,
        unique: true
    },
    meta: {
        createdAt: {
            type: Date,
            default: Date.now()
        },
        updatedAt: {
            type: Date,
            default: Date.now()
        }
    }
});

UserSchema.pre('save', function (next) {
    if( this.isNew ) {
        this.meta.createdAt = this.meta.updatedAt = Date.now()
    } else {
        this.meta.updatedAt = Date.now()
    }

    next()
})

UserSchema.pre('save', function (next) {
    if(!this.isModified('userPass')) return next()

    bcrypt.genSalt(SALT_WORK_FACTOR, (err, salt) =>{
        if (err) return next(err)

        bcrypt.hash(this.userPass, salt, (error, hash) => {
            if (error) return next(error)

            this.userPass = hash
            next()
        })
    })
})

UserSchema.methods = {
    /**
     * @param _password 传入的
     * @param password 数据库里的
     */
    comparePassword: (_password, password) => {
      return new Promise((resolve, reject) => {
          bcrypt.compare(_password, password, (err, isMatch) => {
              if(!err) resolve(isMatch)
              else reject(err)
          })
      })
    },

    /**
     * 登陆次数限制， 先不做。。。要改上面的数据结构并增加虚拟字段
     * @param user
     */
    incLoginAttempts: (user) => {

    }
}

mongoose.model('User', UserSchema)